package cn.uncode.baas.server.internal.module.acl;

import java.util.Map;

import cn.uncode.baas.server.dto.RestGroup;
import cn.uncode.baas.server.dto.RestRole;
import cn.uncode.baas.server.dto.RestUserAcl;
import cn.uncode.baas.server.internal.context.RestContextManager;
import cn.uncode.baas.server.service.IResterService;
import cn.uncode.baas.server.utils.DataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AclModule implements IAclModule {
	
	@Autowired
    private IResterService resterService;

	@Override
	public void saveRole(Object param) {
		Map<String, Object> map = DataUtils.convert2Map(param);
		RestRole restRole = RestRole.valueOf(map);
		restRole.setBucket(RestContextManager.getContext().getBucket());
		resterService.insertRestRole(restRole.getBucket(), restRole.getName(), restRole.getDesc());
	}

	@Override
	public void userAuth(Object param) {
		Map<String, Object> map = DataUtils.convert2Map(param);
		RestUserAcl restUserAcl = RestUserAcl.valueOf(map);
		restUserAcl.setBucket(RestContextManager.getContext().getBucket());
		int count = resterService.countRestGroup(restUserAcl.getBucket(), restUserAcl.getUsername());
		if(count > 0){
			resterService.updateRestUserAcl(restUserAcl.getBucket(), restUserAcl.getUsername(), restUserAcl.getGroups(), restUserAcl.getRoles());
		}else{
			resterService.insertRestUserAcl(restUserAcl.getBucket(), restUserAcl.getUsername(), restUserAcl.getGroups(), restUserAcl.getRoles());
		}
	}

	@Override
	public void removeRole(String name) {
		resterService.deleteRestRole(RestContextManager.getContext().getBucket(), name);
	}

	@Override
	public void saveGroup(Object param) {
		Map<String, Object> map = DataUtils.convert2Map(param);
		RestGroup restGroup = RestGroup.valueOf(map);
		restGroup.setBucket(RestContextManager.getContext().getBucket());
		int count = resterService.countRestGroup(restGroup.getBucket(), restGroup.getName());
		if(count > 0){
			resterService.updateRestGroup(restGroup.getBucket(), restGroup.getName(), restGroup.getDesc(), restGroup.getRoles());
		}else{
			resterService.insertRestGroup(restGroup.getBucket(), restGroup.getName(), restGroup.getDesc(), restGroup.getRoles());
		}
	}

	@Override
	public void removeGroup(String name) {
		resterService.deleteRestGroup(RestContextManager.getContext().getBucket(), name);
	}

	@Override
	public void removeUserAuth(String username) {
		resterService.deleteRestUserAcl(RestContextManager.getContext().getBucket(), username);
	}

}
